require 'rexml/document'
require 'net/http'
class FlashVar < ActiveRecord::Base
  belongs_to :work
  validates_uniqueness_of :vid, :scope=>:work_id, :message => 'same'
  validates_presence_of :vid, :message => 'vid is null'
  has_many :d_results
  belongs_to :space_type

  def add_result( scan = Scan.find(:first, :order => "id desc") )
    DResult.create :scan_id => scan.id, :flash_var_id => self.id, :d_count => get_danmu_count.size
  end

  def get_danmu_count
    require 'zlib'
    Net::HTTP.version_1_2
    response = nil
    Net::HTTP.start("d.#{BILI_PATH}"){ |http| response = http.get( "/" + self.vid )}
    doc = nil
    while
      begin
        doc = REXML::Document.new(Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(response.body))
      rescue
        doc = REXML::Document.new(response.body)
      end
      break
    end
    ori_data = doc.elements.to_a( "//d")
    ori_data.size
  end
end
